<?php
/**
 * Plugin Name: 异次元工单提交API插件
 * Plugin URI: https://www.mysqil.com/
 * Description: 用于对接异次元工单提交API的WordPress插件，可以创建独立页面模板并在后台设置API地址
 * Version: 1.0
 * Author: 松坂有希
 * Author URI: https://space.bilibili.com/701864046
 */

// 防止直接访问文件
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

// 插件初始化
function wp_ticket_plugin_init() {
    // 加载文本域用于国际化
    load_plugin_textdomain( 'wp-ticket-plugin', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
}
add_action( 'plugins_loaded', 'wp_ticket_plugin_init' );

// 插件卸载函数
function wp_ticket_plugin_uninstall() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'ticket_api_settings';
    $wpdb->query( "DROP TABLE IF EXISTS $table_name" );
}
register_uninstall_hook( __FILE__, 'wp_ticket_plugin_uninstall' );

// 创建数据库表用于存储API设置
function wp_ticket_plugin_install() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'ticket_api_settings';
    $charset_collate = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE IF NOT EXISTS $table_name (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        api_url varchar(255) NOT NULL,
        created_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
        updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL,
        PRIMARY KEY  (id)
    ) $charset_collate;";

    require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
    dbDelta( $sql );

    // 检查是否已存在设置，如果不存在则插入默认设置
    $existing_settings = $wpdb->get_row( "SELECT * FROM $table_name WHERE id = 1" );
    if ( ! $existing_settings ) {
        $wpdb->insert(
            $table_name,
            array(
                'api_url' => 'http://localhost/gongd/api/api.php',
            )
        );
    }
}
register_activation_hook( __FILE__, 'wp_ticket_plugin_install' );

// 添加后台菜单
function wp_ticket_plugin_add_admin_menu() {
    add_options_page(
        '工单API设置',
        '工单API设置',
        'manage_options',
        'wp-ticket-plugin',
        'wp_ticket_plugin_settings_page'
    );
}
add_action( 'admin_menu', 'wp_ticket_plugin_add_admin_menu' );

// 注册设置
function wp_ticket_plugin_register_settings() {
    // 添加设置字段并指定保存回调函数
    register_setting( 'wp-ticket-plugin-settings', 'ticket_api_url', 'wp_ticket_plugin_save_settings' );
}
add_action( 'admin_init', 'wp_ticket_plugin_register_settings' );

//  settings页面回调
function wp_ticket_plugin_settings_page() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'ticket_api_settings';
    $settings = $wpdb->get_row( "SELECT * FROM $table_name WHERE id = 1" );
    ?>
    <div class="wrap">
        <h1>工单API设置</h1>
        <form method="post" action="options.php">
            <?php settings_fields( 'wp-ticket-plugin-settings' ); ?>
            <?php do_settings_sections( 'wp-ticket-plugin-settings' ); ?>
            <table class="form-table">
                <tr valign="top">
                    <th scope="row">API地址</th>
                    <td><input type="text" name="ticket_api_url" value="<?php echo esc_attr( $settings->api_url ); ?>" size="50" /></td>
                </tr>
            </table>
            <?php submit_button(); ?>
        </form>
    </div>
    <?php
}

// 保存设置回调函数
function wp_ticket_plugin_save_settings( $input ) {
    global $wpdb;
    $table_name = $wpdb->prefix . 'ticket_api_settings';
    $wpdb->update(
        $table_name,
        array( 'api_url' => sanitize_text_field( $input ) ),
        array( 'id' => 1 )
    );
    return $input;
}

// 创建页面模板
function wp_ticket_plugin_add_page_template( $templates ) {
    $templates['ticket-submission.php'] = '工单提交页面';
    return $templates;
}
add_filter( 'theme_page_templates', 'wp_ticket_plugin_add_page_template' );

// 加载页面模板
function wp_ticket_plugin_load_page_template( $template ) {
    if ( is_page_template( 'ticket-submission.php' ) ) {
        $plugin_template = plugin_dir_path( __FILE__ ) . 'templates/ticket-submission.php';
        if ( file_exists( $plugin_template ) ) {
            return $plugin_template;
        }
    }
    return $template;
}
add_filter( 'template_include', 'wp_ticket_plugin_load_page_template' );

// 短代码 - 显示工单提交表单
function wp_ticket_plugin_shortcode() {
    ob_start();
    // 获取API设置
    global $wpdb;
    $table_name = $wpdb->prefix . 'ticket_api_settings';
    $settings = $wpdb->get_row( "SELECT * FROM $table_name WHERE id = 1" );
    
    // 记录当前使用的API地址
    error_log('工单插件使用的API地址: ' . $settings->api_url);

    // 添加更多调试信息
    error_log('WordPress 版本: ' . get_bloginfo('version'));
    error_log('当前用户: ' . (is_user_logged_in() ? wp_get_current_user()->user_login : '未登录'));
    error_log('当前页面URL: ' . get_permalink());
    
    ?>
    <div style="max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #ddd; border-radius: 5px;">
        <h2>提交工单</h2>
        <form id="ticket-form" method="post">
            <div style="margin-bottom: 15px;">
                <label for="qqNumber" style="display: block; margin-bottom: 5px; font-weight: bold;">QQ号码</label>
                <input type="text" id="qqNumber" name="qqNumber" required style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box;">
            </div>
            <div style="margin-bottom: 15px;">
                <label for="feedbackType" style="display: block; margin-bottom: 5px; font-weight: bold;">反馈类型</label>
                <select id="feedbackType" name="feedbackType" required style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box;">
                    <option value="">请选择反馈类型</option>
                    <option value="bug">Bug报告</option>
                    <option value="suggestion">功能建议</option>
                    <option value="question">咨询问题</option>
                    <option value="other">其他问题</option>
                </select>
            </div>
            <div style="margin-bottom: 15px;">
                <label for="severity" style="display: block; margin-bottom: 5px; font-weight: bold;">问题严重程度</label>
                <select id="severity" name="severity" required style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box;">
                    <option value="">请选择严重程度</option>
                    <option value="1">1 - 轻微</option>
                    <option value="2">2 - 一般</option>
                    <option value="3">3 - 重要</option>
                    <option value="4">4 - 严重</option>
                    <option value="5">5 - 紧急</option>
                </select>
            </div>
            <div style="margin-bottom: 15px;">
                <label for="description" style="display: block; margin-bottom: 5px; font-weight: bold;">问题描述</label>
                <textarea id="description" name="description" rows="5" required style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box;"></textarea>
            </div>
            <button type="submit" id="submit-ticket" style="background-color: #4CAF50; color: white; padding: 10px 15px; border: none; border-radius: 4px; cursor: pointer;">提交工单</button>
        </form>
        <div id="ticket-response"></div>
    </div>
    <script>
        document.getElementById('ticket-form').addEventListener('submit', function(e) {
            e.preventDefault();
            const formData = new FormData(this);
            const xhr = new XMLHttpRequest();
            const apiUrl = '<?php echo esc_js( $settings->api_url ); ?>';
            
            console.log('提交工单到API地址:', apiUrl);
            
            // 添加API请求前的调试信息
            console.log('准备发送请求到:', apiUrl);
            console.log('请求参数:', formData);

            xhr.open('POST', apiUrl, true);
            
            // 设置超时时间为30秒
            xhr.timeout = 30000;
            
            xhr.onload = function() {
                console.log('API响应状态:', xhr.status);
                console.log('API响应内容:', xhr.responseText);
                
                if (xhr.status === 200) {
                    try {
                        const response = JSON.parse(xhr.responseText);
                        const responseDiv = document.getElementById('ticket-response');
                        if (response.success) {
                            responseDiv.innerHTML = '<div style="margin-top: 15px; padding: 10px; background-color: #dff0d8; border: 1px solid #d6e9c6; color: #3c763d; border-radius: 4px;">' + response.message + '，工单ID：' + response.ticket_id + '</div>';
                            document.getElementById('ticket-form').reset();
                        } else {
                            // 处理API返回的错误信息
                            let errorMessage = response.message;
                            if (Array.isArray(errorMessage)) {
                                errorMessage = errorMessage.join('<br>');
                            }
                            responseDiv.innerHTML = '<div style="margin-top: 15px; padding: 10px; background-color: #f2dede; border: 1px solid #ebccd1; color: #a94442; border-radius: 4px;">' + errorMessage + '</div>';
                        }
                    } catch (error) {
                        console.error('解析响应失败:', error);
                        document.getElementById('ticket-response').innerHTML = '<div style="margin-top: 15px; padding: 10px; background-color: #f2dede; border: 1px solid #ebccd1; color: #a94442; border-radius: 4px;">解析响应失败: ' + error.message + '</div>';
                    }
                } else if (xhr.status === 404) {
                    document.getElementById('ticket-response').innerHTML = '<div style="margin-top: 15px; padding: 10px; background-color: #f2dede; border: 1px solid #ebccd1; color: #a94442; border-radius: 4px;">API地址不存在，请检查设置中的API地址是否正确</div>';
                } else if (xhr.status === 500) {
                    document.getElementById('ticket-response').innerHTML = '<div style="margin-top: 15px; padding: 10px; background-color: #f2dede; border: 1px solid #ebccd1; color: #a94442; border-radius: 4px;">服务器内部错误，请稍后再试</div>';
                } else {
                    document.getElementById('ticket-response').innerHTML = '<div style="margin-top: 15px; padding: 10px; background-color: #f2dede; border: 1px solid #ebccd1; color: #a94442; border-radius: 4px;">请求失败，状态码: ' + xhr.status + '</div>';
                }
            };
            
            xhr.ontimeout = function() {
                console.error('API请求超时');
                document.getElementById('ticket-response').innerHTML = '<div style="margin-top: 15px; padding: 10px; background-color: #f2dede; border: 1px solid #ebccd1; color: #a94442; border-radius: 4px;">请求超时，请稍后再试</div>';
            };
            
            xhr.onerror = function() {
                console.error('网络错误');
                document.getElementById('ticket-response').innerHTML = '<div style="margin-top: 15px; padding: 10px; background-color: #f2dede; border: 1px solid #ebccd1; color: #a94442; border-radius: 4px;">网络错误，请检查API地址是否正确或稍后再试</div>';
            };
            
            xhr.send(formData);
        });
    </script>

    <?php
    return ob_get_clean();
}
add_shortcode( 'ticket_form', 'wp_ticket_plugin_shortcode' );
?>